package com.lagou.common.service;

import com.lagou.common.dao.FlashSaleDao;
import com.lagou.common.dao.OrderDao;
import com.lagou.common.pojo.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

@Service
public class OrderService {

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private FlashSaleDao flashSaleDao;

    public void save(Order order) {
        orderDao.save(order);
    }

    public List<Order> findAllByStatus(String status) {
       return orderDao.findAllByStatus(status);
    }

    public List<Order> findAllByUserId(String userId) { return orderDao.findAllByUserId(userId); }

    public List<Order> findAll() {
        return orderDao.findAll();
    }

    public Order findById(Long id) {
        Optional<Order> optional = orderDao.findById(id);

        if (optional.isEmpty()) {
            return null;
        } else {
            return optional.get();
        }
    }

    /**
     * 创建订单并去库存
     * @param order
     */
    @Transactional
    public void createOrder(Order order) {
        orderDao.save(order);

        flashSaleDao.decreaseOneStock(1L);

//        if (Math.random() >= 0) {
//            throw new RuntimeException("故意抛出异常");
//        }
    }


    public void overdueAndCancel(Long orderId) {
        orderDao.overdueAndCancel(orderId);
    }


    public int payOrder(Long orderId) {
        return orderDao.payOrder(orderId);
    }
}
